<script lang="ts" setup>
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import type { FileCategoriesApi } from '#/api/infra/filecategories';

import { ref } from 'vue';

import { Page, useVbenModal } from '@vben/common-ui';
import { downloadFileFromBlobPart } from '@vben/utils';

import { message } from 'ant-design-vue';

import { ACTION_ICON, TableAction, useVbenVxeGrid } from '#/adapter/vxe-table';
import {
  defalutFileCategories,
  deleteFileCategories,
  exportFileCategories,
  getFileCategoriesList,
} from '#/api/infra/filecategories';
import { $t } from '#/locales';

import { useGridColumns, useGridFormSchema } from './data';
import Detail from './modules/detail.vue';
import FileappTable from './modules/fileapp-table.vue';
import Form from './modules/form.vue';

const [FormModal, formModalApi] = useVbenModal({
  connectedComponent: Form,
  destroyOnClose: true,
});
const [DetailModal, detailModalApi] = useVbenModal({
  connectedComponent: Detail,
  destroyOnClose: true,
});
const [FileappTableModal, fileappTableModalApi] = useVbenModal({
  connectedComponent: FileappTable,
  destroyOnClose: true,
  showConfirmButton: false,
});
/** 切换树形展开/收缩状态 */
const isExpanded = ref(true);
function toggleExpand() {
  isExpanded.value = !isExpanded.value;
  gridApi.grid.setAllTreeExpand(isExpanded.value);
}

/** 刷新表格 */
function onRefresh() {
  gridApi.query();
}

/** 查看文件对象分类 */
function handleDetail(row: FileCategoriesApi.FileCategories) {
  detailModalApi.setData(row).open();
}

/** 创建文件对象分类 */
function handleCreate() {
  formModalApi.setData({}).open();
}

/** 编辑文件对象分类 */
function handleEdit(row: FileCategoriesApi.FileCategories) {
  formModalApi.setData(row).open();
}

/** 应用文件授权 */
function handleFileApp(row: FileCategoriesApi.FileCategories) {
  fileappTableModalApi.setData(row).open();
}
/** 设为默认分类 */
async function handleDefault(row: FileCategoriesApi.FileCategories) {
  const hideLoading = message.loading({
    content: $t('ui.actionMessage.updating', [row.name]),
    duration: 0,
    key: 'action_process_msg',
  });
  try {
    await defalutFileCategories(row.id!);
    message.success($t('ui.actionMessage.updateSuccess', [row.name]));
    onRefresh();
  } finally {
    hideLoading();
  }
}
/** 新增下级文件对象分类 */
function handleAppend(row: FileCategoriesApi.FileCategories) {
  formModalApi.setData({ parentId: row.id, configId: row.configId }).open();
}

/** 删除文件对象分类 */
async function handleDelete(row: FileCategoriesApi.FileCategories) {
  const hideLoading = message.loading({
    content: $t('ui.actionMessage.deleting', [row.name]),
    duration: 0,
  });
  try {
    await deleteFileCategories(row.id!);
    message.success({
      content: $t('ui.actionMessage.deleteSuccess', [row.id]),
    });
    onRefresh();
  } finally {
    hideLoading();
  }
}

/** 导出表格 */
async function handleExport() {
  const data = await exportFileCategories(await gridApi.formApi.getValues());
  downloadFileFromBlobPart({ fileName: '文件分类.xls', source: data });
}

const [Grid, gridApi] = useVbenVxeGrid({
  formOptions: {
    schema: useGridFormSchema(),
  },
  gridOptions: {
    id: 'FileCategories-grid',
    columns: useGridColumns(),
    height: 'auto',
    treeConfig: {
      parentField: 'parentId',
      rowField: 'id',
      transform: true,
      expandAll: true,
      reserve: true,
    },
    pagerConfig: {
      enabled: false,
    },
    proxyConfig: {
      ajax: {
        query: async (_, formValues) => {
          return await getFileCategoriesList(formValues);
        },
      },
    },
    rowConfig: {
      keyField: 'id',
      isHover: true,
    },
    toolbarConfig: {
      refresh: true,
      search: true,
    },
  } as VxeTableGridOptions<FileCategoriesApi.FileCategories>,
  gridEvents: {},
});
</script>

<template>
  <Page auto-content-height>
    <FormModal @success="onRefresh" />
    <DetailModal @success="onRefresh" />
    <FileappTableModal @success="onRefresh" />
    <Grid table-title="文件分类列表">
      <template #toolbar-tools>
        <TableAction
          :actions="[
            {
              label: isExpanded ? '收缩' : '展开',
              type: 'primary',
              onClick: toggleExpand,
            },
            {
              label: $t('ui.actionTitle.create', ['文件分类']),
              type: 'primary',
              icon: ACTION_ICON.ADD,
              auth: ['infra:file-categories:create'],
              onClick: handleCreate,
            },
            {
              label: $t('ui.actionTitle.export'),
              type: 'primary',
              icon: ACTION_ICON.DOWNLOAD,
              auth: ['infra:file-categories:export'],
              onClick: handleExport,
            },
          ]"
        />
      </template>
      <template #actions="{ row }">
        <TableAction
          :actions="[
            {
              label: '查看',
              type: 'link',
              icon: ACTION_ICON.VIEW,
              auth: ['infra:file-categories:query'],
              onClick: handleDetail.bind(null, row),
            },
            {
              label: '新增下级',
              type: 'link',
              icon: ACTION_ICON.ADD,
              auth: ['infra:file-categories:create'],
              onClick: handleAppend.bind(null, row),
            },
            {
              label: $t('common.edit'),
              type: 'link',
              icon: ACTION_ICON.EDIT,
              auth: ['infra:file-categories:update'],
              onClick: handleEdit.bind(null, row),
            },
          ]"
          :drop-down-actions="[
            {
              label: '默认分类',
              type: 'link',
              auth: ['infra:file-categories:update'],
              popConfirm: {
                title: `是否要将${row.name}设为默认分类？`,
                confirm: handleDefault.bind(null, row),
              },
            },
            {
              label: '应用授权',
              type: 'link',
              auth: ['infra:file-categories:create'],
              onClick: handleFileApp.bind(null, row),
            },
            {
              label: $t('common.delete'),
              type: 'link',
              auth: ['infra:file-categories:delete'],
              popConfirm: {
                title: $t('ui.actionMessage.deleteConfirm', [row.id]),
                confirm: handleDelete.bind(null, row),
              },
            },
          ]"
        />
      </template>
    </Grid>
  </Page>
</template>
